//
//  NetAPI.m
//  Coin
//
//  Created by yangy on 2018/6/27.
//  Copyright © 2018年 zzg. All rights reserved.
//

#import "NetAPI.h"
#import <AFNetworking.h>

@implementation NetRequest

+ (NetRequest *)sharedNetAPI
{
    static NetRequest *netApi = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        netApi = [[NetRequest alloc] init];
    });
    return netApi;
}

+ (NSURLSessionDataTask *)getWithUrl:(NSString *)url parameters:(id)parameters success:(NAResponseSuccess)success fail:(NAResponseFail)fail showHUD:(BOOL)showHUD
{
    return [self baseRequestType:BHNetworkRequestTypeGET url:url params:parameters success:success fail:fail showHUD:showHUD includeParameterToURL:NO];
}

+ (NSURLSessionDataTask*) postWithUrl:(NSString*) url
                           parameters:(id) parameters
                              success:(NAResponseSuccess) success
                                 fail:(NAResponseFail) fail
                              showHUD:(BOOL) showHUD includeParameterToURL:(BOOL) isInclude
{
    return [self baseRequestType:BHNetworkRequestTypePOST url:url params:parameters success:success fail:fail showHUD:showHUD includeParameterToURL:isInclude];
}

+ (NSURLSessionDataTask *)baseRequestType:(BHNetworkRequestType)type
                                 url:(NSString *)url
                              params:(NSDictionary *)params
                             success:(NAResponseSuccess)success
                                fail:(NAResponseFail)fail
                             showHUD:(BOOL)showHUD
                    includeParameterToURL:(BOOL) isInclude
{
    if(url == nil){
        return nil;
    }
    
    NSString *requestURL = [NSString stringWithFormat:@"https://%@%@",ServerURL,url];
    NSString *urlStr = [NSURL URLWithString:requestURL]? requestURL:[self strUTF8Encoding:requestURL];
    
    NSURLSessionDataTask *task = nil;
    AFHTTPSessionManager *manager = [self getAFManager:url includeParameterToURL:isInclude];
    if(type == BHNetworkRequestTypeGET){
        task = [manager GET:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if(![NSThread isMainThread]){
                dispatch_async(dispatch_get_main_queue(), ^{
                   success(responseObject);
                });
            }else{
                  success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if(![NSThread isMainThread]){
                dispatch_async(dispatch_get_main_queue(), ^{
                     fail(error);
                });
            }else{
                 fail(error);
            }
        }];
    }else if(type == BHNetworkRequestTypePOST){
       task = [manager POST:urlStr parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
           if(![NSThread isMainThread]){
               dispatch_async(dispatch_get_main_queue(), ^{
                    success(responseObject);
               });
           }else{
                success(responseObject);
           }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if(![NSThread isMainThread]){
                dispatch_async(dispatch_get_main_queue(), ^{
                    fail(error);
                });
            }else{
                fail(error);
            }
        }];
    }
    return task;
}


+ (AFHTTPSessionManager *)getAFManager:(NSString*) method includeParameterToURL:(BOOL) isInclude{
    
    //[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//设置请求数据为json
    // 默认post请求参数保存body,导致服务器娶不到参数
    // HTTPMethodsEncodingParametersInURI 参数保存在url之后
    manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"GET",@"HEAD"]];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//设置返回数据为json
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"image/*"]];
    if(isInclude){
         manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:@[@"POST",@"GET",@"HEAD"]];
    }
    
    if([PlistCommon loginModel] && [PlistCommon loginModel].UserID){
        NSString *tokenStr = [NSString stringWithFormat:@"bearer %@",[PlistCommon loginModel].Token];
        [manager.requestSerializer setValue:tokenStr forHTTPHeaderField:@"Authorization"];
    }
    return manager;
}

+ (void)startMonitoring
{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status)
        {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
//                [LXNetworking sharedLXNetworking].networkStats=StatusUnknown;
                break;
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                //[LXNetworking sharedLXNetworking].networkStats=StatusNotReachable;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                //[LXNetworking sharedLXNetworking].networkStats = StatusReachableViaWWAN;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                //[LXNetworking sharedLXNetworking].networkStats=StatusReachableViaWiFi;
                break;
        }
    }];
    [mgr startMonitoring];
}

+ (NSString *)strUTF8Encoding:(NSString *)str {
    return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end
